<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <input type="text" placeholder="用户名" id="username" />
        <input type="text" placeholder="密码" id="password" />
        <input type="submit" value="登录">
    </div>
</body>
<script>
    username.value = parseCookie('username')
    password.value = parseCookie('password')

    /**
     * 获得指定名称target的cookie值 cookie='username=tom'
     * @date 2020-10-09
     * @param {any} target cookie的名称 username
     * @returns {any} target名称对应的cookie的值 tom
     */
    function parseCookie(target) {
        //获得cookie='username=tom; age=20; gender=男'
        // username=tom --->key=username value=tom
        let str = document.cookie
        //把字符串转换成数组
        str = str.split("; ")
        //遍历数组把数组中的key=value值封装成对象
        let object = {}
        for (let i = 0; i < str.length; i++) {
            let el = str[i] //找到=的下标
            let index = el.indexOf('=')
            //截取=前的字符串
            let key = el.substring(0, index) //username
            //截取=后的字符串
            let value = el.substring(index + 1) //tom
            //把key作为object对象的属性，value作为key的值
            object[key] = value
        }
        return object[target]
    }
</script>

</html>